package edu.psu.ist131.lib;

import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Vector;

public class FileDb
{

//    private static String dbUrl = "localhost/t1";
//    private static String dbUsername = "root";
//    private static String dbPassword = "root";
    private static String dbPath;
    private static ODatabaseObjectTx db;
    
    private Exception caughtException;
    
    public Exception GetCaughtException()
    {
        return caughtException;
    }


    public FileDb() throws IOException
    {
        InitializeDatabase();
    }


    public void InitializeDatabase() throws IOException
    {
        File tmpdir = createTempDirectory();
        dbPath = tmpdir.getAbsolutePath();
        db = new ODatabaseObjectTx("local:" + tmpdir.getAbsolutePath());
        db.getEntityManager().registerEntityClass(FileMetadata.class);
        db.create();
    }


    public Collection<FileMetadata> Query(String queryStr)
    {
        OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(queryStr);
        try
        {
            List<FileMetadata> result = db.query(query);
            return result;
        }
        catch(Exception ex)
        {
            caughtException = ex;                   // be sure to check this when troubleshooting
            return new Vector<FileMetadata>();
        }
    }


    public void AddFilesToDb(Collection<FileMetadata> d1)
    {
        for(FileMetadata file : d1)
        {
            db.save(file);
        }        
    }


    public static File createTempDirectory() throws IOException
    {
        final File temp;
        temp = File.createTempFile("temp" + Long.toString(System.nanoTime()), "");
        if(!(temp.delete()))
        {
            throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
        }
        if(!(temp.mkdir()))
        {
            throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
        }
        return (temp);
    }
}
